//= require <framework/w3c/events/CustomEvent>
//= require <framework/w3c/components/ModalScreen>

namespace("w3c.Application", {
	'@inherits' : w3c.HtmlComponent,
	screens: {},
	
	preInitialize : function(model, element) {
		window.application = this;
		this.parent(model, element);
		window.sfx={};
		this.addEventListener("changescreen", this.loadScreen.bind(this), true);
		this.addEventListener("changeapplication", this.loadApplication.bind(this), true);
		window.optmode = this.optmode;
		this.setModalOverlay();
		this.setBrowserClassname();
		return this;
    },
	
	setBrowserClassname : function(){
		try {
			this.addClass(browser.DeviceInfo.OS, document.body);
			this.addClass(browser.DeviceInfo.browser, document.body);
			document.body.setAttribute("browser", browser.DeviceInfo.browser);
			document.body.setAttribute("os", browser.DeviceInfo.OS);
			this.addClass("application")
		} catch(e) {
			try{
				console.warn("There was a problem setting the agent/device information on the <body> tag.")
				console.warn(" |--> " + e.message)
			} catch(e){}
		}
	},
	
	getScrollbarWidth : window.getScrollbarWidth,
	
	initialize : function(){
		//window.application = this;
		//this.droppables = [];
		
		//this.setModalOverlay();
		/*this.modalscreen = new controls.ModalScreen;
		this.modalscreen.start(function(){
		    application.appendChild(self.modalscreen.element)
			self.modalscreen.hide();
		});*/
	},
	
	start : function(model, element){
		var args = arguments;
		var self=this;
		try {
			this.setModel(model);
        	this.setElement(element);
			this.initializeChildNodes();
			this.rerouteEvents();
			this.initialize(arguments[0]);
		} 
		catch(e){
			alert(this.namespace + "#start() caused an error:\n" + e.message);
		}
		return this;
	},
	
	 setModalOverlay: function () {
        var ms = document.createElement("div");
        this.addClass("ModalOverlay", ms);
        this.element.appendChild(ms);

        this.setStyles({
            width: xClientWidth() + "px",
            height: xClientHeight() + "px"
        }, ms);

        this.modaloverlay = ms;
        jQuery(ms).click(function (e) {
            application.demodalize();
        });
    },
	
	modalize: function (aControl, x, y) {
        if (this.last_modalized_control) {
            this.last_modalized_control.parentNode.removeChild(this.last_modalized_control);
            this.last_modalized_control = null;
        }
        this.last_modalized_control = aControl;
        if (x && y) {
            this.setStyles({
                "z-index": this.absoluteZindex(),
                top: y + "px",
                left: x + "px"
            }, aControl);
        }
        else {
            this.setStyles({ "z-index": this.absoluteZindex() }, aControl);
        }
        aControl.style.opacity = 0;
        this.element.appendChild(aControl);
        this.setStyles({
            width: 4000 + "px",
            height: 4000 + "px",
            display: "block"
        }, this.modaloverlay);
        this.setStyles({ "overflow": "hidden" }, document.body);
		
        //jQuery(aControl).animate({ "opacity": 1 }, 700);
    },

    demodalize: function (aControl) {
        var self = this;
        self.last_modalized_control.parentNode.removeChild(self.last_modalized_control);
        self.last_modalized_control = null;

        self.setStyles({ display: "none" }, self.modaloverlay);
        self.setStyles({ "overflow": "auto" }, document.body);
    },
	
	scrollToLeft : function(x){
		var scrollContainer = (browser.DeviceInfo.browser=="Firefox") ? 
				document.documentElement:document.body;
			if(jQuery){
				jQuery(scrollContainer).animate({scrollLeft : x});	
			}
			else {window.scrollTo(x,0);}
	},
	
	optmode : function(){
		if(!config.performance || (typeof config.performance == "undefined")) {
			return false;
		};
		return true;	
	},
	
	setOptmode : function(bool){
		config.performance = bool;
	},
	
	droppables:[],
	
	addDropContainer : function(component){
		this.droppables.push(component.element);
	},
	
	getAllDropContainers : function(){
		return this.droppables;
	},
	
	getAcceptableDropContainersByInstance : function(obj_instance){
		var containers = this.getAllDropContainers();
		var acceptableDropContainers = [];
		for(var i=0; i<=containers.length-1; i++) {
			var container=containers[i];
			var container_prototype=container.prototype;
			if(container_prototype && container_prototype.accepts && container_prototype.accepts(obj_instance) && !obj_instance.constrained()) {
				acceptableDropContainers.push(container);
			}
		};

		return acceptableDropContainers;
	},
	
	defaultScreen : function(){
		return "Splash"
	},
	
	globalzindex : 600000,
	
	absoluteZindex : function(nodeReference){
		this.globalzindex = this.globalzindex + 1;
		return this.globalzindex;
	},
	
	registerScreen : function(name, screen) {
		if(!this.screenregistry) {
			this.screenregistry = {};
		}
		this.screenregistry[name] = screen;
	},
	
	getScreen : function(name, screen) {
		return (this.screenregistry) ? this.screenregistry[name]:null;
	},
	
	loadScreen: function (title) {
        this.removeAllScreens();
        if (this.screens[title]) {
            this.querySelector(".screens").appendChild(this.screens[title].element);
        }
        else {
            try {
                var s = new screens[title];
                s.start();
                this.screens[title] = s;
                this.querySelector(".screens").appendChild(s.element);
            }
            catch (e) { }
        }
        if (this.screens[title]) {
            this.activeScreen = this.screens[title];
        }
        document.body.className = "";
        this.addClass(title, document.body);
        
    },
	
	removeAllScreens: function () {
        toArray(this.querySelectorAll(".screens .screen")).forEach(function (screen) {
            screen.parentNode.removeChild(screen);
        });
    },

	bringToFront : function(newScreen, oldScreen){
		jQuery(newScreen.element).fadeIn("slow", function() {
			newScreen.activate();
		}.bind(this));
		if (oldScreen) {
			jQuery(oldScreen.element).fadeOut("fast", function(){
				oldScreen.setStyles({display: "none"});
				oldScreen.deactivate();
			}.bind(this));
		}
	},
	
	loadApplication : function(e) {
		e=e.detail;
		//logger.info("Redirecting to: " + e.url);
		location.href = e.url
	},
	
	
    innerHTML:"<div></div>",
	
	scrollX : function () {return window.pageXOffset ? window.pageXOffset : document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft;},
	scrollY : function () {return window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;},
	mouseX  : function(e)  {return e.clientX ? e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) : e.pageX;},
	mouseX  : function(e)  {return e.clientY ? e.clientY + (document.documentElement.scrollTop || document.body.scrollTop) : e.pageY;},
	elementFromPoint : function(x,y){
		//var xoffset,yoffset;
		if(browser.DeviceInfo.browser=="Firefox" || browser.DeviceInfo.browser=="Chrome") {x=x;y=y;}
		else if(browser.DeviceInfo.browser=="Opera" || browser.DeviceInfo.browser=="Safari") {
			x=x+this.scrollX();
			y=y+this.scrollY();
		}
		var drpzone = document.elementFromPoint(x, y);
		return drpzone;
	}
});
